﻿using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Text;

namespace Auth.Utility.Common
{
    /// <summary>
    /// 动态属性转换约定
    /// </summary>
    /// <remarks>
    /// 处理场景 树形结构数据 后台代码实体定义 为 Id Childrens 但是前台树形控件所需数据结构为  id,nodes
    /// 这个时候可以使用该属性约定转换类 动态设置 序列化后字段名称
    /// </remarks>
    /// <example>
    ///     JsonSerializerSettings setting = new JsonSerializerSettings();
    ///     setting.ContractResolver = new PropsContractResolver(new Dictionary<string, string> { { "Id", "id" }, { "Text", "text" }, { "Childrens", "nodes" } });
    ///     string AA = JsonConvert.SerializeObject(cc, Formatting.Indented, setting);
    /// </example>
    public class PropsContractResolver : DefaultContractResolver
    {
        Dictionary<string, string> dict_props = null;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="props">传入的属性数组</param>
        public PropsContractResolver(Dictionary<string, string> dictPropertyName)
        {
            //指定字段要序列化成什么名称
            this.dict_props = dictPropertyName;
        }

        protected override string ResolvePropertyName(string propertyName)
        {
            string newPropertyName = string.Empty;
            if (dict_props != null && dict_props.TryGetValue(propertyName, out newPropertyName))
            {
                return newPropertyName;
            }
            else
            {
                return base.ResolvePropertyName(propertyName);
            }
        }
    }
}
